import { PrismaClient } from '@prisma/client';
import { testConfig } from '../config/testConfig';
import prisma from '../lib/prisma';

interface TableInfo {
  tablename: string;
}

beforeAll(async () => {
  process.env.JWT_SECRET = testConfig.jwt.secret;
  process.env.LOG_DIR = testConfig.logging.dir;
  
  // 确保连接到测试数据库
  await prisma.$connect();
});

afterAll(async () => {
  await prisma.$disconnect();
});

beforeEach(async () => {
  // 清理所有测试数据
  const tablenames = await prisma.$queryRaw<TableInfo[]>`
    SELECT tablename 
    FROM pg_tables
    WHERE schemaname='public'
  `;

  const tables = tablenames
    .map(({ tablename }: { tablename: string }) => tablename)
    .filter((name: string) => !name.includes('_prisma_'))
    .filter((name: string) => !name.includes('schema_migrations'));

  try {
    await prisma.$transaction([
      // 禁用外键检查
      prisma.$executeRawUnsafe('SET CONSTRAINTS ALL DEFERRED'),
      
      // 清空所有表
      ...tables.map((table: string) => 
        prisma.$executeRawUnsafe(`TRUNCATE TABLE "${table}" CASCADE`)
      ),
      
      // 重新启用外键检查
      prisma.$executeRawUnsafe('SET CONSTRAINTS ALL IMMEDIATE'),
    ]);
  } catch (error) {
    console.error('清理测试数据失败:', error);
    throw error;
  }
});
